package com.df.springmvc.workflow.trace.dao;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.activiti.engine.identity.User;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.stereotype.Repository;
import com.common.bean.SQLResultBean;
import com.df.springmvc.workflow.ActicityDao;

/**
 * 本类只做数据库操作处理
 * @author Turner
 */
@Repository
public class TraceManageDao extends ActicityDao{
	/**
	 * *
	 * @param sql
	 *            查询的SQL
	 * @param param_HashMap
	 *            查询参数
	 * @param i
	 *            从第几天开始
	 * @param j
	 *            显示多少条数据
	 * @return
	 * @throws Exception
	 */
	public ArrayList<Object[]> query(HashMap<String,String> map,Object[] attribute,int i,int j) throws Exception{
		// TODO Auto-generated method stub
		ArrayList<Object[]> list=new ArrayList<Object[]>();
		TaskQuery query=taskService.createTaskQuery();
		HistoricTaskInstanceQuery hisTaskQuery=historyService.createHistoricTaskInstanceQuery();
		if(map.get("insId") != null && !"".equals(map.get("insId"))){
			query=query.processInstanceId(map.get("insId"));
			hisTaskQuery=hisTaskQuery.processInstanceId(map.get("insId"));
		}
		int index=1;
		if("crt".equalsIgnoreCase(map.get("type"))){
			List<Task> insList=query.orderByTaskCreateTime().asc().list();
			for(Task ins:insList){
				Object[] objects=new Object[8];
				int t=0;
				objects[t++]="";
				objects[t++]=index++;
				objects[t++]=ins.getProcessInstanceId();
				objects[t++]=ins.getId();
				objects[t++]=ins.getName();
				objects[t++]=ins.getAssignee();
				String title="";
				if(true){
					SQLResultBean sqlResultBean;
					try{
						sqlResultBean=querySqlToSQLResultBean("select title from S_WF_ProcInst_Info where wf_proc_inst_id=?",new Object[]{ins.getProcessInstanceId()});
						ArrayList<HashMap<String,Object>> mapList=sqlResultBean.getMapList();
						for(HashMap<String,Object> hashMap:mapList){
							title="" + hashMap.get("title");
						}
					}catch(Exception e){
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				objects[t++]=title;
				list.add(objects);
			}
		}
		if("his".equalsIgnoreCase(map.get("type"))){
			List<HistoricTaskInstance> hisList=hisTaskQuery.finished().orderByProcessInstanceId().asc().orderByTaskCreateTime().asc().listPage(0,500);
			for(HistoricTaskInstance hisIns:hisList){
				Object[] objects=new Object[8];
				int t=0;
				objects[t++]="";
				objects[t++]=index++;
				objects[t++]=hisIns.getProcessInstanceId();
				objects[t++]=hisIns.getId();
				objects[t++]=hisIns.getName();
				objects[t++]=hisIns.getAssignee();
				list.add(objects);
			}
		}
		return list;
	}
	@Override
	public Object del(HashMap<String,Object> map) throws Exception{
		// TODO Auto-generated method stub
		if(true){
			runtimeService.deleteProcessInstance("" + map.get("processInstanceId"),"" + map.get("reason"));
			return "1";
		}
		return super.del(map);
	}
	public ArrayList<HashMap<String,Object>> getListByExecutionID(String ExecutionID,String processInstanceId){
		ArrayList<HashMap<String,Object>> list=new ArrayList<HashMap<String,Object>>();
		HistoricTaskInstanceQuery hisTaskQuery=historyService.createHistoricTaskInstanceQuery();
		List<HistoricTaskInstance> hisList=hisTaskQuery.processInstanceId(processInstanceId).orderByProcessInstanceId().asc().orderByTaskCreateTime().asc().list();
		// 查询
		org.apache.log4j.Logger.getLogger(getClass()).info("hisList:" + hisList.size());
		SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for(HistoricTaskInstance hisIns:hisList){
			HashMap<String,Object> map=new HashMap<String,Object>();
			map.put("id",hisIns.getId());
			map.put("name",hisIns.getName());
			if(hisIns.getAssignee() == null){
				ArrayList<String> candidateUser=new ArrayList<String>();
				try{
					List<Task> taskList=taskService.createTaskQuery().processInstanceId(processInstanceId).list();
					for(Task task:taskList){
						if(hisIns.getId().equalsIgnoreCase(task.getId())){
							List<IdentityLink> linksForTask=taskService.getIdentityLinksForTask(task.getId());
							for(IdentityLink identityLink:linksForTask){
								if("candidate".equalsIgnoreCase(identityLink.getType())){
									if(identityLink.getGroupId() != null){
										for(String tmp:identityLink.getGroupId().split(",")){
											List<User> list2=identityService.createUserQuery().memberOfGroup(tmp).list();
											for(User user:list2){
												if(!candidateUser.contains(user.getId())){
													candidateUser.add(user.getId());
												}
											}
										}
									}
									if(identityLink.getUserId() != null){
										for(String tmp:identityLink.getUserId().split(",")){
											if(!candidateUser.contains(tmp)){
												candidateUser.add(tmp);
											}
										}
									}
								}
							}
							map.put("assignee","候:" + candidateUser);
						}
					}
				}catch(Exception e){
					// TODO: handle exception
					e.printStackTrace();
				}finally{
				}
			}else{
				map.put("assignee",hisIns.getAssignee());
			}
			if(hisIns.getClaimTime() == null){
				map.put("claimTime","");
			}else{
				map.put("claimTime",df.format(hisIns.getClaimTime()));
			}
			if(hisIns.getCreateTime() == null){
				map.put("createTime","");
			}else{
				map.put("createTime",df.format(hisIns.getCreateTime()));
			}
			if(hisIns.getEndTime() == null){
				map.put("EndTime","");
			}else{
				map.put("EndTime",df.format(hisIns.getEndTime()));
			}
			if(hisIns.getDurationInMillis() == null){
				map.put("Duration","0S");
			}else{
				Long l=hisIns.getDurationInMillis();
				long D=l / 1000 / 60 / 60 / 24;
				long H=l / 1000 / 60 / 60 % 24;
				long M=l / 1000 / 60 % 60;
				long S=l / 1000 % 60;
				map.put("Duration",D + "D " + H + "H " + M + "M " + S + "S");
			}
			map.put("Description",hisIns.getDescription());
			list.add(map);
		}
		return list;
	}
	public InputStream tracePic(String ExecutionID,String processInstanceId) throws Exception{
		// TODO Auto-generated method stub
		// Task task=taskService.createTaskQuery().taskId(taskId).singleResult();
		// String executionId = task.getExecutionId();
		ProcessInstance processInstance=runtimeService.createProcessInstanceQuery().processInstanceId(ExecutionID).singleResult();
		org.apache.log4j.Logger.getLogger(getClass()).info("查看：" + "ExecutionID:" + ExecutionID + ":" + processInstance);
		if(processInstance != null){
			String processDefinitionId=processInstance.getProcessDefinitionId();
			BpmnModel bpmnModel=repositoryService.getBpmnModel(processDefinitionId);
			// 得到正在执行的环节
			List<String> activeActivityIds=runtimeService.getActiveActivityIds(ExecutionID);
			String activityFontName=processEngine.getProcessEngineConfiguration().getActivityFontName();
			String labelFontName=processEngine.getProcessEngineConfiguration().getLabelFontName();
			InputStream diagramStream=new DefaultProcessDiagramGenerator().generateDiagram(bpmnModel,"png",activeActivityIds,Collections.<String>emptyList(),activityFontName,labelFontName,null,1.0);
			return diagramStream;
		}else{
			HistoricProcessInstance singleResult=historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
			String processDefinitionId=singleResult.getProcessDefinitionId();
			BpmnModel bpmnModel=repositoryService.getBpmnModel(processDefinitionId);
			// 得到正在执行的环节
			List<String> activeActivityIds=new ArrayList<String>();
			String activityFontName=processEngine.getProcessEngineConfiguration().getActivityFontName();
			String labelFontName=processEngine.getProcessEngineConfiguration().getLabelFontName();
			InputStream diagramStream=new DefaultProcessDiagramGenerator().generateDiagram(bpmnModel,"png",activeActivityIds,Collections.<String>emptyList(),activityFontName,labelFontName,null,1.0);
			return diagramStream;
		}
	}
	public ArrayList<Object[]> portlet(HashMap<String,String> paramMap,Object[] attribute,int i,int j){
		// TODO Auto-generated method stub
		ArrayList<Object[]> list=new ArrayList<Object[]>();
		String userId="" + paramMap.get("userId");
		TaskQuery query=taskService.createTaskQuery();
		if("admin".equals(userId)){
		}else{
			query.taskCandidateOrAssigned(userId);
		}
		List<Task> insList=query.orderByTaskCreateTime().asc().list();
		for(Task task:insList){
			Object[] objects=new Object[9];
			int t=0;
			objects[t++]="";
			objects[t++]=task.getId();
			objects[t++]=task.getName();
			String user="";
			boolean assigneeStatus=false;
			List<IdentityLink> linksForTask=taskService.getIdentityLinksForTask(task.getId());
			ArrayList<String> candidateUser=new ArrayList<String>();
			for(IdentityLink identityLink:linksForTask){
				if("candidate".equalsIgnoreCase(identityLink.getType())){
					if(identityLink.getGroupId() != null){
						for(String tmp:identityLink.getGroupId().split(",")){
							List<User> list2=identityService.createUserQuery().memberOfGroup(tmp).list();
							for(User user_:list2){
								if(!candidateUser.contains(user_.getId())){
									candidateUser.add(user_.getId());
								}
							}
						}
					}
					if(identityLink.getUserId() != null){
						for(String tmp:identityLink.getUserId().split(",")){
							if(!candidateUser.contains(tmp)){
								candidateUser.add(tmp);
							}
						}
					}
				}
				if("assignee".equalsIgnoreCase(identityLink.getType())){
					user=task.getAssignee();
					assigneeStatus=true;
				}
			}
			objects[t++]=task.getAssignee() == null?"候:" + candidateUser:task.getAssignee();
			objects[t++]=task.getProcessInstanceId();
			String title=task.getDescription();
			if("".equals(title)){// 大卫修改：由流程说明替换为任务说明。
				SQLResultBean sqlResultBean;
				try{
					sqlResultBean=querySqlToSQLResultBean("select title from S_WF_ProcInst_Info where wf_proc_inst_id=?",new Object[]{task.getProcessInstanceId()});
					ArrayList<HashMap<String,Object>> mapList=sqlResultBean.getMapList();
					for(HashMap<String,Object> hashMap:mapList){
						title="" + hashMap.get("title");
					}
				}catch(Exception e){
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			objects[t++]=title;
			String status="";
			if("提交".equals(task.getName())){
				status="草稿";
			}else{
				System.out.println("".equalsIgnoreCase(user.trim()));
				status=assigneeStatus == false?"未签收":"处理中";
			}
			objects[t++]=status;
			list.add(objects);
		}
		return list;
	}
	/**
	 * wf_proc_task_formName
	 * wf_proc_task_formUrl
	 * wf_proc_task_formWidth
	 * wf_proc_task_formHeight
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	public Object queryFormUrl(HashMap<String,String> paramMap) throws Exception{
		// TODO Auto-generated method stub
		String taskId=paramMap.get("taskId");
		Task task=taskService.createTaskQuery().taskId(taskId).singleResult();
		if(task == null){
			throw new Exception("任务不存在，请重新更新任务信息。");
		}
		String defId=task.getProcessDefinitionId();
		String taskKey=task.getTaskDefinitionKey();
		String InsId=task.getProcessInstanceId();
		HashMap<String,Object> hashMap=new HashMap<String,Object>();
		if(true){
			String sql="select wf_proc_task_formName name,wf_proc_task_formUrl url,wf_proc_task_formWidth as w ,wf_proc_task_formHeight as h from S_WF_Task_Info where status=1 and wf_proc_def_id=:wf_proc_def_id and wf_proc_task_id=:wf_proc_task_id";
			HashMap<String,Object> tmp=new HashMap<String,Object>();
			tmp.put("wf_proc_def_id",defId);
			tmp.put("wf_proc_task_id",taskKey);
			SQLResultBean resultBean=querySqlToSQLResultBean(sql,tmp,0,0);
			ArrayList<HashMap<String,Object>> mapList=resultBean.getMapList();
			for(HashMap<String,Object> t:mapList){
				hashMap.putAll(t);
			}
		}
		if(true){
			String sql="select wf_proc_form_guid as guid from S_WF_ProcInst_Info where wf_proc_inst_id=:wf_proc_inst_id";
			HashMap<String,Object> tmp=new HashMap<String,Object>();
			tmp.put("wf_proc_inst_id",InsId);
			SQLResultBean resultBean=querySqlToSQLResultBean(sql,tmp,0,0);
			ArrayList<HashMap<String,Object>> mapList=resultBean.getMapList();
			for(HashMap<String,Object> t:mapList){
				hashMap.putAll(t);
			}
		}
		return hashMap;
	}
}
